package bdcin.mineracao;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexReader;
import org.apache.lucene.queryParser.QueryParser;
import org.apache.lucene.search.Hits;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.Searcher;

import bdcin.classesbasicas.Documento;
import bdcin.excecoes.BuscarException;
import bdcin.fachada.BDCIn;
import bdcin.fachada.IBDCIn;
import bdcin.mineracao.analysis.br.BrazilianAnalyzer;
import bdcin.util.Constants;



 public class ConsultaDocumentos {
 
  public ConsultaDocumentos() {}

  public List<Documento> buscarDocumentosConteudo(String consulta) throws Exception {
    String index = "index";
    String field = "contents";    
    index = Constants.localIndice;
       
    IndexReader reader = IndexReader.open(index);
       
    Searcher searcher = new IndexSearcher(reader);
    Analyzer analyzer = new BrazilianAnalyzer();
        
      QueryParser parser = new QueryParser(field, analyzer);
                      
      Query query = parser.parse(consulta);
      
      System.out.println("Pesquisando por: " + query.toString(field));

      Hits hits = searcher.search(query);   

      List<Documento> documentos = converterHits(hits);
       
    reader.close();
    
    return documentos;
    
  }
  
  private List<Documento> converterHits(Hits hits) throws CorruptIndexException, IOException, BuscarException{
		IBDCIn facade = BDCIn.getFacade();
		List<Documento> documentos = new ArrayList<Documento>();
	
		for(int i = 0; i < hits.length(); i++){
			Document doc = hits.doc(i);			
			Long id = Long.valueOf(doc.getField("idBD").stringValue());
			Documento documento=null;
			try {
				documento = facade.buscarDocumento(id);
			} catch (BuscarException e) {
				throw new BuscarException("Erro ao converter hits!");
			}
			documentos.add(documento);			
		}
	
		return documentos;				
		
	}
  
}
